library(readr)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(plotly)
## Carregando pacotes exigidos: ggplot2
## Warning: package 'ggplot2' was built under R version 4.3.3
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(readxl)
library(sf)
## Warning: package 'sf' was built under R version 4.3.3
## Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE
library(tidyr)
library(classInt)
## Warning: package 'classInt' was built under R version 4.3.3
library(ggspatial)
## Warning: package 'ggspatial' was built under R version 4.3.3
if(!require('basedosdados'))install.packages("basedosdados");library(basedosdados)
## Carregando pacotes exigidos: basedosdados
## Warning: package 'basedosdados' was built under R version 4.3.3
if(!require('usethis'))install.packages("usethis");library(usethis)
## Carregando pacotes exigidos: usethis
## Warning: package 'usethis' was built under R version 4.3.3
if(!require('jsonlite'))install.packages("jsonlite");library(jsonlite)
## Carregando pacotes exigidos: jsonlite
if(!require('haven'))install.packages("haven");library(haven)
## Carregando pacotes exigidos: haven
rm_accent <- function(x) iconv(x, to = "ASCII//TRANSLIT")
series <- read_excel("~/GitHub/AULAS/Dados/Tabela 4099.xlsx", skip = 3)
## New names:
## • `` -> `...2`
names(series) <- c('data','valor')
series$data <- gsub("º trimestre ", "-", series$data)
series$Ano <- as.numeric(substr(series$data, 3, 6))
## Warning: NAs introduzidos por coerção
series$Trimestre <- as.numeric(substr(series$data, 1, 1))
## Warning: NAs introduzidos por coerção
series <- series %>%
  filter(Ano >= 2013 & Ano < 2023) %>%
  mutate(data = paste0(Ano, "-Q", Trimestre)) %>%
  select(data, valor)
series$valor <- as.numeric(series$valor)
## Warning: NAs introduzidos por coerção

Base Corporate

corporate <- read_csv("~/GitHub/MIM/dados/cretool/corporate.csv")
## New names:
## Rows: 106077 Columns: 17
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (2): Classe Buildings, Status dbl (15): ...1, Ano, Trimestre, Estoque Total
## (m²), Vacância (m²), Taxa de V...
## ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
## Specify the column types or set `show_col_types = FALSE` to quiet this message.
## • `` -> `...1`
names(corporate) <- gsub('[$]','S',gsub('[/]','_',gsub('[)]','',gsub('[(]','',gsub('%','porc', gsub(' ','_',rm_accent(names(corporate))))))))


corporate$AnoTri = paste0(corporate$Ano,'-Q',corporate$Trimestre)



corporate_filtro <- corporate %>%
  filter(!(Status %in% c("Em Construção","Em Projeto","Fora de Mercado")))


corporate_filtro1 <- corporate %>%
  filter(!(Status %in% c("Em Construção","Em Construção (Retrofit)","Em Projeto","Fora de Mercado")))

Rais Base

df_capitais = read.csv("~/GitHub/AULAS/Dados/df_capitais.csv")
df_capitais$AnoTri = paste0(df_capitais$ano,'-Q',df_capitais$quater)
#-----------------------------------------------------------------------
# Passo 1: Preparação dos dados (seu código, sem alterações)
# Assumindo que 'corporate_filtro', 'corporate_filtro1' e 'series' já existem
#-----------------------------------------------------------------------

# Dados para as barras (Estoque)
temp1 <- corporate_filtro[corporate_filtro$Ano >= 2013 & corporate_filtro$Ano < 2023,]
temp1 <- temp1 %>% dplyr::group_by(AnoTri) %>%
         dplyr::summarise(Estoque_Total_m2 = sum(Estoque_Total_m2),
                          Estoque_vago_m2 = sum(Vacancia_m2)) %>%
         # Correção: O cálculo deve ser feito após o summarise
         dplyr::mutate(Estoque_oculpado_m2 = Estoque_Total_m2 - Estoque_vago_m2,
                       taxa_Estoque_vago_m2 = Estoque_vago_m2 / Estoque_Total_m2,
                       taxa_Estoque_oculpado_m2 = Estoque_oculpado_m2 / Estoque_Total_m2)

# Dados para a primeira linha (Taxa de Vacância Calculada)
temp2 <- corporate_filtro1[corporate_filtro1$Ano >= 2013 & corporate_filtro1$Ano < 2023,]
temp2$tava_de_vacancia_calc <- (temp2$Vacancia_m2/temp2$Estoque_Total_m2)*100
temp <- temp2 %>% dplyr::group_by(AnoTri) %>% dplyr::summarise(tava_de_vacancia_calc_mean = mean(tava_de_vacancia_calc), units = n())



#-----------------------------------------------------------------------
# Passo 2: Construção do Gráfico com Eixo Y Secundário
#-----------------------------------------------------------------------

fig <- plot_ly()

# --- EIXO Y PRIMÁRIO (Esquerda) ---
# Trace 0: Barras para o Estoque Total
fig <- fig %>% add_trace(x = temp1$AnoTri,
                         y = temp1$Estoque_Total_m2,
                         mode = 'lines+markers',
                         type = 'scatter',
                         line = list(shape = "spline", width = 4),
                         name = 'Estoque Total (m²)') # Nome para a legenda

# --- EIXO Y SECUNDÁRIO (Direita) ---
# Trace 1: Linha para a sua Taxa de Vacância Média
fig <- fig %>% add_trace(x = temp$AnoTri,
                         y = temp$tava_de_vacancia_calc_mean,
                         mode = 'lines',
                         type = 'scatter',
                         line = list(shape = "spline", width = 4, dash = 'dash'),
                         name = 'Taxa de Vacância (%)', # Nome para a legenda
                         yaxis = "y2") # <-- ASSOCIAR AO EIXO Y2

# Trace 2: Linha para a Taxa de Vacância do BC
fig <- fig %>% add_trace(x = df_capitais$AnoTri,
                         y = df_capitais$total,
                         mode = 'lines+markers',
                         type = 'scatter',
                         connectgaps = TRUE,
                         line = list(shape = "spline", width = 4),
                         name = 'Pessoas Ocupadas') 

# --- CONFIGURAÇÃO DOS EIXOS (LAYOUT) ---
fig <- fig %>% layout(
    title = 'Análise de Estoque, Taxa de Vacância e Empregos (2013-2022)',
    
    # Configura o eixo Y primário (esquerda)
    yaxis = list(
        title = 'Total'
    ),
    
    # Configura o eixo Y secundário (direita)
    yaxis2 = list(
        overlaying = "y",  # Sobrepõe o eixo 'y' primário
        side = "right",    # Posiciona no lado direito
        title = 'Taxa de Vacância (%)', # Título do eixo
        showgrid = FALSE,  # Remove a grade para não poluir
        zeroline = FALSE,  # Remove a linha do zero
        range = c(0, max(temp$tava_de_vacancia_calc_mean) * 1.2), # Ajusta o range
        tickformat = "%.1f%%" # Formata os ticks para mostrar o símbolo de %
    ),
    
    # Configura o eixo X
    xaxis = list(
        title = 'Ano-Trimestre <br><sup>Fonte: IBGE-PNADc e Buildings</sup>'
    ),
    
    # Outras configurações úteis
    legend = list(
        orientation = 'h', # Legenda na horizontal
        xanchor = 'center',
        x = 0.5,
        y = -0.2
    ),
    barmode = 'group' # Modo das barras
)

# Exibir o gráfico
fig

Financiamento imobiliário com taxas de mercado - Pós-fixado referenciado em TR

Financiamento imobiliário com taxas reguladas - Pós-fixado referenciado em TR

Pessoa Física - Financiamento imobiliário com taxas de mercado - Pós-fixado referenciado em IPCA

Pessoa Física - Financiamento imobiliário com taxas de reguladas - Pós-fixado referenciado em IPCA

read_csv("~/GitHub/AULAS/Dados/fin_imob_taxas_mercado_pos_TR.csv") -> fin_imob_taxas_mercado_pos_TR
## Rows: 1750 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): Segmento, Modalidade, InstituicaoFinanceira, TaxaJurosAoMes, TaxaJ...
## dbl  (1): Posicao
## date (1): DataConsulta
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
read_csv("~/GitHub/AULAS/Dados/fin_imob_taxas_reguladas_pos_TR.csv") -> fin_imob_taxas_reguladas_pos_TR
## Rows: 2023 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): Segmento, Modalidade, InstituicaoFinanceira, TaxaJurosAoMes, TaxaJ...
## dbl  (1): Posicao
## date (1): DataConsulta
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
read_csv("~/GitHub/AULAS/Dados/fin_imob_taxas_mercado_pos_IPCA.csv") -> fin_imob_taxas_mercado_pos_IPCA
## Rows: 381 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): Segmento, Modalidade, InstituicaoFinanceira, TaxaJurosAoMes, TaxaJ...
## dbl  (1): Posicao
## date (1): DataConsulta
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
read_csv("~/GitHub/AULAS/Dados/fin_imob_taxas_reguladas_pos_IPCA.csv") -> fin_imob_taxas_reguladas_pos_IPCA
## Rows: 234 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): Segmento, Modalidade, InstituicaoFinanceira, TaxaJurosAoMes, TaxaJ...
## dbl  (1): Posicao
## date (1): DataConsulta
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
fin_imob_taxas_mercado_pos_TR <- fin_imob_taxas_mercado_pos_TR %>% 
                                      select(DataConsulta, TaxaJurosAoAno, InstituicaoFinanceira) %>%  
                                      filter(InstituicaoFinanceira == 'BCO BRADESCO S.A.' |
                                             InstituicaoFinanceira == 'CAIXA ECONOMICA FEDERAL' |
                                             InstituicaoFinanceira == 'ITAÚ UNIBANCO S.A.' | 
                                             InstituicaoFinanceira == 'BCO SANTANDER (BRASIL) S.A.' |
                                             InstituicaoFinanceira == 'BCO DO BRASIL S.A.'
                                             )%>%
                                      spread(InstituicaoFinanceira,TaxaJurosAoAno)

fin_imob_taxas_mercado_pos_TR$DataConsulta <- as.Date(fin_imob_taxas_mercado_pos_TR$DataConsulta, "%d-%m-%Y")
fin_imob_taxas_mercado_pos_TR <- fin_imob_taxas_mercado_pos_TR[order(fin_imob_taxas_mercado_pos_TR$DataConsulta),]

fin_imob_taxas_mercado_pos_TR$`BCO BRADESCO S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_TR$`BCO BRADESCO S.A.`))
fin_imob_taxas_mercado_pos_TR$`BCO SANTANDER (BRASIL) S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_TR$`BCO SANTANDER (BRASIL) S.A.`))
fin_imob_taxas_mercado_pos_TR$`CAIXA ECONOMICA FEDERAL` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_TR$`CAIXA ECONOMICA FEDERAL`))
fin_imob_taxas_mercado_pos_TR$`ITAÚ UNIBANCO S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_TR$`ITAÚ UNIBANCO S.A.`))
fin_imob_taxas_mercado_pos_TR$`BCO DO BRASIL S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_TR$`BCO DO BRASIL S.A.`))


fig <- plot_ly(x = fin_imob_taxas_mercado_pos_TR$DataConsulta)
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_TR$`BCO BRADESCO S.A.`, name = "BRADESCO", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_TR$`BCO SANTANDER (BRASIL) S.A.`, name = "SANTANDER", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_TR$`CAIXA ECONOMICA FEDERAL`, name = "CAIXA", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_TR$`ITAÚ UNIBANCO S.A.`, name = "ITAÚ", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_TR$`BCO DO BRASIL S.A.`, name = "BCO DO BRASIL", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% layout(title = "Financiamento Imobiliário com taxas de mercados - Pós-Fixados Referenciado em TR",
                      xaxis = list(title = "Data<br><sup>Fonte: Bacen</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig
fin_imob_taxas_reguladas_pos_TR <- fin_imob_taxas_reguladas_pos_TR %>% 
                                      select(DataConsulta, TaxaJurosAoAno, InstituicaoFinanceira) %>%  
                                      filter(InstituicaoFinanceira == 'BCO BRADESCO S.A.' |
                                             InstituicaoFinanceira == 'CAIXA ECONOMICA FEDERAL' |
                                             InstituicaoFinanceira == 'ITAÚ UNIBANCO S.A.' | 
                                             InstituicaoFinanceira == 'BCO SANTANDER (BRASIL) S.A.' |
                                             InstituicaoFinanceira == 'BCO DO BRASIL S.A.'
                                             )%>%
                                      spread(InstituicaoFinanceira,TaxaJurosAoAno)
fin_imob_taxas_reguladas_pos_TR[fin_imob_taxas_reguladas_pos_TR$DataConsulta=="2022-05-01",4]=NA
fin_imob_taxas_reguladas_pos_TR$DataConsulta <- as.Date(fin_imob_taxas_reguladas_pos_TR$DataConsulta, "%d-%m-%Y")
fin_imob_taxas_reguladas_pos_TR <- fin_imob_taxas_reguladas_pos_TR[order(fin_imob_taxas_reguladas_pos_TR$DataConsulta),]

fin_imob_taxas_reguladas_pos_TR$`BCO BRADESCO S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_TR$`BCO BRADESCO S.A.`))
fin_imob_taxas_reguladas_pos_TR$`BCO SANTANDER (BRASIL) S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_TR$`BCO SANTANDER (BRASIL) S.A.`))
fin_imob_taxas_reguladas_pos_TR$`CAIXA ECONOMICA FEDERAL` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_TR$`CAIXA ECONOMICA FEDERAL`))
fin_imob_taxas_reguladas_pos_TR$`ITAÚ UNIBANCO S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_TR$`ITAÚ UNIBANCO S.A.`))
fin_imob_taxas_reguladas_pos_TR$`BCO DO BRASIL S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_TR$`BCO DO BRASIL S.A.`))


fig <- plot_ly(x = fin_imob_taxas_reguladas_pos_TR$DataConsulta)
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_TR$`BCO BRADESCO S.A.`, name = "BRADESCO", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_TR$`BCO SANTANDER (BRASIL) S.A.`, name = "SANTANDER", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_TR$`CAIXA ECONOMICA FEDERAL`, name = "CAIXA", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_TR$`ITAÚ UNIBANCO S.A.`, name = "ITAÚ", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_TR$`BCO DO BRASIL S.A.`, name = "BCO DO BRASIL", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% layout(title = "Financiamento Imobiliário com taxas de reguladas - Pós-Fixados Referenciado em TR",
                      xaxis = list(title = "Data<br><sup>Fonte: Bacen</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig
fin_imob_taxas_mercado_pos_IPCA <- fin_imob_taxas_mercado_pos_IPCA %>% 
                                      select(DataConsulta, TaxaJurosAoAno, InstituicaoFinanceira) %>%  
                                      filter(InstituicaoFinanceira == 'CAIXA ECONOMICA FEDERAL' |
                                             InstituicaoFinanceira == 'BCO DO BRASIL S.A.'
                                             )%>%
                                      spread(InstituicaoFinanceira,TaxaJurosAoAno)

fin_imob_taxas_mercado_pos_IPCA$DataConsulta <- as.Date(fin_imob_taxas_mercado_pos_IPCA$DataConsulta, "%d-%m-%Y")
fin_imob_taxas_mercado_pos_IPCA <- fin_imob_taxas_mercado_pos_IPCA[order(fin_imob_taxas_mercado_pos_IPCA$DataConsulta),]

fin_imob_taxas_mercado_pos_IPCA$`CAIXA ECONOMICA FEDERAL` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_IPCA$`CAIXA ECONOMICA FEDERAL`))
fin_imob_taxas_mercado_pos_IPCA$`BCO DO BRASIL S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_mercado_pos_IPCA$`BCO DO BRASIL S.A.`))


fig <- plot_ly(x = fin_imob_taxas_mercado_pos_IPCA$DataConsulta)
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_IPCA$`CAIXA ECONOMICA FEDERAL`, name = "CAIXA", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% add_trace(y = fin_imob_taxas_mercado_pos_IPCA$`BCO DO BRASIL S.A.`, name = "BCO DO BRASIL", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% layout(title = "Financiamento Imobiliário com taxas de mercado - Pós-fixado referenciado em IPCA",
                      xaxis = list(title = "Data<br><sup>Fonte: Bacen</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig
fin_imob_taxas_reguladas_pos_IPCA <- fin_imob_taxas_reguladas_pos_IPCA %>% 
                                      select(DataConsulta, TaxaJurosAoAno, InstituicaoFinanceira) %>%  
                                      filter(InstituicaoFinanceira == 'BCO BRADESCO S.A.' |
                                             InstituicaoFinanceira == 'CAIXA ECONOMICA FEDERAL' |
                                             InstituicaoFinanceira == 'ITAÚ UNIBANCO S.A.' | 
                                             InstituicaoFinanceira == 'BCO SANTANDER (BRASIL) S.A.' |
                                             InstituicaoFinanceira == 'BCO DO BRASIL S.A.'
                                             )%>%
                                      spread(InstituicaoFinanceira,TaxaJurosAoAno)

fin_imob_taxas_reguladas_pos_IPCA$DataConsulta <- as.Date(fin_imob_taxas_reguladas_pos_IPCA$DataConsulta, "%d-%m-%Y")
fin_imob_taxas_reguladas_pos_IPCA <- fin_imob_taxas_reguladas_pos_IPCA[order(fin_imob_taxas_reguladas_pos_IPCA$DataConsulta),]

fin_imob_taxas_reguladas_pos_IPCA$`CAIXA ECONOMICA FEDERAL` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_IPCA$`CAIXA ECONOMICA FEDERAL`))
fin_imob_taxas_reguladas_pos_IPCA$`BCO DO BRASIL S.A.` = as.numeric(gsub(",", ".", fin_imob_taxas_reguladas_pos_IPCA$`BCO DO BRASIL S.A.`))


fig <- plot_ly(x = fin_imob_taxas_reguladas_pos_IPCA$DataConsulta)
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_IPCA$`CAIXA ECONOMICA FEDERAL`, name = "CAIXA", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% add_trace(y = fin_imob_taxas_reguladas_pos_IPCA$`BCO DO BRASIL S.A.`, name = "BCO DO BRASIL", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% layout(title = "Financiamento Imobiliário com taxas de regulado - Pós-fixado referenciado em IPCA",
                      xaxis = list(title = "Data<br><sup>Fonte: Bacen</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig
fipezap_serieshistoricas <- read_excel("~/GitHub/AULAS/Dados/fipezap-serieshistoricas.xlsx", 
    sheet = "São Paulo", range = "B4:V214")
## New names:
## • `Total` -> `Total...2`
## • `1D` -> `1D...3`
## • `2D` -> `2D...4`
## • `3D` -> `3D...5`
## • `4D` -> `4D...6`
## • `Total` -> `Total...7`
## • `1D` -> `1D...8`
## • `2D` -> `2D...9`
## • `3D` -> `3D...10`
## • `4D` -> `4D...11`
## • `Total` -> `Total...12`
## • `1D` -> `1D...13`
## • `2D` -> `2D...14`
## • `3D` -> `3D...15`
## • `4D` -> `4D...16`
## • `Total` -> `Total...17`
## • `1D` -> `1D...18`
## • `2D` -> `2D...19`
## • `3D` -> `3D...20`
## • `4D` -> `4D...21`
fig <- plot_ly()
fig <- fig %>% add_trace(x = fipezap_serieshistoricas$Data, y = as.numeric(fipezap_serieshistoricas$Total...12)*100, name = "Valor médio do m²", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
## Warning in add_trace(., x = fipezap_serieshistoricas$Data, y =
## as.numeric(fipezap_serieshistoricas$Total...12) * : NAs introduzidos por
## coerção
fig <- fig %>% layout(title = "Índice de Preços de Imóveis Residenciais",
                      xaxis = list(title = "Data<br><sup>Fonte: FipeZap</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig
temp = fipezap_serieshistoricas %>% filter(Data >= "2012-01-01")
fig <- plot_ly()
fig <- fig %>% add_trace(x = temp$Data, y = as.numeric(temp$Total...12)*100, name = "FipeZap", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline"))
fig <- fig %>% add_trace(x = fin_imob_taxas_reguladas_pos_TR$DataConsulta, y = fin_imob_taxas_reguladas_pos_TR$`CAIXA ECONOMICA FEDERAL`, name = "CAIXA", type = 'scatter', mode = 'lines+markers', connectgaps = TRUE,line = list(shape = "spline")) 
fig <- fig %>% layout(title = "Índice de Preços de Imóveis Residenciais",
                      xaxis = list(title = "Data<br><sup>Fonte: FipeZap</sup>"),
                      yaxis = list (title = "Taxa Juros ao Ano"))
fig

load rais

lista_de_dfs <- list()

for(i in 1:100){
  # Crie o caminho do arquivo
  caminho_arquivo <- paste0("~/GitHub/AULAS/Dados/RAIS/RAIS_est_geocoded", i, ".csv")
  
  # Leia o CSV forçando 'clascnae20' a ser texto e adicione à lista
  lista_de_dfs[[i]] <- read_csv(
    caminho_arquivo,
    col_types = cols(clascnae20 = col_character(),
                     attributes.UnitName = col_character(),
                     attributes.AddNum = col_character(),
                     sbclas20 = col_character(),
                     attributes.LevelName= col_character())
  )
}

# Junte todos os data frames da lista em um único data frame
RAIS_est_geocoded <- bind_rows(lista_de_dfs)
RAIS_est_geocoded = RAIS_est_geocoded[RAIS_est_geocoded$score>=98 & RAIS_est_geocoded$indraisneg == 0 & RAIS_est_geocoded$ibgesubsetor != 24,]
RAIS_est_geocoded <- RAIS_est_geocoded %>% 
  drop_na(long, lat)
shp_sp <- st_read("~/GitHub/AULAS/Dados/shp_base/Distritos_2017_region.shp")
## Reading layer `Distritos_2017_region' from data source 
##   `C:\Users\onurb\Documents\GitHub\AULAS\Dados\shp_base\Distritos_2017_region.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 134 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY, XYZ
## Bounding box:  xmin: 275295.9 ymin: 7337234 xmax: 429153.6 ymax: 7435608
## z_range:       zmin: 0 zmax: 0
## Projected CRS: Corrego Alegre 1970-72 / UTM zone 23S
shp_sp <- st_zm(shp_sp)
shp_sp <- st_transform(shp_sp, crs = 4326)
shp_sp <- st_make_valid(shp_sp)
shp_sp <- st_read("~/GitHub/AULAS/Dados/shp_base/Distritos_2017_region.shp")
## Reading layer `Distritos_2017_region' from data source 
##   `C:\Users\onurb\Documents\GitHub\AULAS\Dados\shp_base\Distritos_2017_region.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 134 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY, XYZ
## Bounding box:  xmin: 275295.9 ymin: 7337234 xmax: 429153.6 ymax: 7435608
## z_range:       zmin: 0 zmax: 0
## Projected CRS: Corrego Alegre 1970-72 / UTM zone 23S
shp_sp <- st_zm(shp_sp)
shp_sp <- st_transform(shp_sp, crs = 4326)
shp_sp <- st_make_valid(shp_sp)
shp_sp_cd <- st_read("~/GitHub/AULAS/Dados/Bairros/DISTRITO_MUNICIPAL_SP_SMDUPolygon.shp")
## Reading layer `DISTRITO_MUNICIPAL_SP_SMDUPolygon' from data source 
##   `C:\Users\onurb\Documents\GitHub\AULAS\Dados\Bairros\DISTRITO_MUNICIPAL_SP_SMDUPolygon.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 96 features and 2 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -46.82625 ymin: -24.00813 xmax: -46.3651 ymax: -23.35659
## Geodetic CRS:  SIRGAS 2000
shp_sp_cd <- st_zm(shp_sp_cd)
shp_sp_cd <- st_transform(shp_sp_cd, crs = 4326)
shp_sp_cd <- st_make_valid(shp_sp_cd)
pin_data <- data.frame(
  nome = "Uberlândia",
  lon = -46.63390630217495,
  lat = -23.550443536456253
)

pin_sf <- st_as_sf(pin_data, coords = c("lon", "lat"), crs = 4326)
RAIS_est_geocoded <- st_as_sf(
  RAIS_est_geocoded,
  coords = c("long", "lat"), # <- longitude primeiro!
  crs = 4326
)
ponto_referencia_geom <- st_point(c(-46.63390630217495, -23.550443536456253))
ponto_referencia_sf <- st_sfc(ponto_referencia_geom, crs = 4326)
RAIS_est_geocoded$distancia_marcozero <- format(st_distance(RAIS_est_geocoded, ponto_referencia_sf), scientific = FALSE)
RAIS_est_geocoded_rich <- st_join(RAIS_est_geocoded, shp_sp)
temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  group_by(NomeDistri) %>%
  summarise(
    total_empregos = sum(as.numeric(estoque), na.rm = TRUE)
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
quantile(temp$total_empregos, probs = seq(0, 1, by = 0.2))
##       0%      20%      40%      60%      80%     100% 
##    261.0  11187.4  21766.8  33063.2  62500.6 430767.0
classIntervals(var = temp$total_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,840,751 possible partitions of this variable into 5 classes
##     [261,29525]   (29525,67549]  (67549,132651] (132651,273770] (273770,430767] 
##              77              33              16               8               1
limites <- c(-Inf, 29525, 67549, 132651, 273770, Inf)

rotulos <- c("0 - 29525", "29525 - 67549", "67549 - 132651", "132651 - 273770", "Mais de 273770")

temp$faixa_empregos <- cut(temp$total_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição de Empregos por Faixa") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

tt <- sum(as.numeric(RAIS_est_geocoded_rich$estoque), na.rm = TRUE)
temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  group_by(NomeDistri) %>%
  summarise(
    share_empregos = sum(as.numeric(estoque), na.rm = TRUE)/tt*100
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
format(quantile(temp$share_empregos, probs = seq(0, 1, by = 0.2)), scientific = FALSE)
##            0%           20%           40%           60%           80% 
## "0.004200175" "0.180034622" "0.350284928" "0.532073646" "1.005798655" 
##          100% 
## "6.932171360"
classIntervals(var = temp$share_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,840,751 possible partitions of this variable into 5 classes
## [0.004200175,0.4751347]    (0.4751347,1.087041]     (1.087041,2.134703] 
##                      77                      33                      16 
##     (2.134703,4.405678]     (4.405678,6.932171] 
##                       8                       1
limites <- c(-Inf, 0.47, 1.08, 2.13, 4.4, Inf)

rotulos <- c("0 - 0.47", "0.47 - 1.08", "1.08 - 2.13", "2.13 - 4.4", "Mais de 4.4")

temp$faixa_empregos <- cut(temp$share_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição do Share Empregos por Faixa") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(startsWith(clascnae20, "620")) %>% # add 63
  group_by(NomeDistri) %>%
  summarise(
    total_empregos = sum(as.numeric(estoque), na.rm = TRUE)
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
quantile(temp$total_empregos, probs = seq(0, 1, by = 0.1))
##      0%     10%     20%     30%     40%     50%     60%     70%     80%     90% 
##     0.0     5.0    10.0    18.0    27.2    52.5   114.6   270.1   873.0  2444.4 
##    100% 
## 33028.0
classIntervals(var = temp$total_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 2,672,670 possible partitions of this variable into 5 classes
##      [0,2268]   (2268,8205]  (8205,18360] (18360,23970] (23970,33028] 
##           111             9             2             1             1
limites <- c(-Inf,2268,8205,18360,23970, Inf)

rotulos <- c("0 - 2268", "2268 - 8205", "8205 - 18360", "18360 - 23970", "Mais de 23970")

temp$faixa_empregos <- cut(temp$total_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição de Empregos por Faixa - Tecnologia") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

tt <- sum(as.numeric(RAIS_est_geocoded_rich[startsWith(RAIS_est_geocoded_rich$clascnae20, "620"),]$estoque), na.rm = TRUE)
temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(startsWith(clascnae20, "620")) %>% # add 63
  group_by(NomeDistri) %>%
  summarise(
    share_empregos = sum(as.numeric(estoque), na.rm = TRUE)/tt*100
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
format(quantile(temp$share_empregos, probs = seq(0, 1, by = 0.2)), scientific = FALSE) ## jenks
##             0%            20%            40%            60%            80% 
## " 0.000000000" " 0.006327352" " 0.017210397" " 0.072511453" " 0.552377819" 
##           100% 
## "20.897977778"
classIntervals(var = temp$share_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 2,672,670 possible partitions of this variable into 5 classes
##        [0,1.435043] (1.435043,5.191592] (5.191592,11.61702] (11.61702,15.16666] 
##                 111                   9                   2                   1 
## (15.16666,20.89798] 
##                   1
limites <- c(-Inf, 1.43, 5.19, 11.61, 15.16, Inf)

rotulos <- c("0 - 1.43", "1.43 - 5.19", "5.19 - 11.61", "11.61 - 15.16", "Mais de 15.16")

temp$faixa_empregos <- cut(temp$share_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição do Share Empregos por Faixa - Tecnologia") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

prefixos <- c(64,66,65,68,69,70,71,73,74,82,78,79,85,86,96,95)

temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), clascnae20)) %>%
  group_by(NomeDistri) %>%
  summarise(
    total_empregos = sum(as.numeric(estoque), na.rm = TRUE)
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
quantile(temp$total_empregos, probs = seq(0, 1, by = 0.2))
##       0%      20%      40%      60%      80%     100% 
##     98.0   2428.4   4604.0   9424.2  23001.2 205401.0
classIntervals(var = temp$total_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,457,445 possible partitions of this variable into 5 classes
##     [98,14145]  (14145,41156]  (41156,68242]  (68242,96128] (96128,205401] 
##             96             26              8              4              1
limites <- c(-Inf, 14145, 41156, 68242, 96128, Inf)

rotulos <- c("0 - 14145", "14145 - 41156", "41156 - 68242", "68242 - 96128", "Mais de 96128")

temp$faixa_empregos <- cut(temp$total_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição de Empregos por Faixa - FIRE e Serviços") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

tt <- sum(as.numeric(RAIS_est_geocoded_rich[grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), RAIS_est_geocoded_rich$clascnae20),]$estoque), na.rm = TRUE)
temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), clascnae20)) %>%
  group_by(NomeDistri) %>%
  summarise(
    share_empregos = sum(as.numeric(estoque), na.rm = TRUE)/tt*100
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
format(quantile(temp$share_empregos, probs = seq(0, 1, by = 0.2)), scientific = FALSE)
##            0%           20%           40%           60%           80% 
## "0.004361821" "0.108084146" "0.204916573" "0.419455858" "1.023746110" 
##          100% 
## "9.142065402"
classIntervals(var = temp$share_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,457,445 possible partitions of this variable into 5 classes
## [0.004361821,0.629571]    (0.629571,1.831787]    (1.831787,3.037341] 
##                     96                     26                      8 
##    (3.037341,4.278501]    (4.278501,9.142065] 
##                      4                      1
limites <- c(-Inf, 0.62, 1.83, 3.03, 4.27, Inf)

rotulos <- c("0 - 0.62", "0.62 - 1.83", "1.83 - 3.03", "3.03 - 4.27", "Mais de 4.27")

temp$faixa_empregos <- cut(temp$share_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição do Share Empregos por Faixa - FIRE e Serviços") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

prefixos <- c(471,472,478,475,474,477,476,453,454,476,478)

temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), clascnae20)) %>%
  group_by(NomeDistri) %>%
  summarise(
    total_empregos = sum(as.numeric(estoque), na.rm = TRUE)
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
quantile(temp$total_empregos, probs = seq(0, 1, by = 0.2))
##      0%     20%     40%     60%     80%    100% 
##    27.0  2172.4  3874.2  5537.2  8007.6 38338.0
classIntervals(var = temp$total_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,082,785 possible partitions of this variable into 5 classes
##     [27,3611]   (3611,7076]  (7076,11741] (11741,19721] (19721,38338] 
##            53            51            19             8             4
limites <- c(-Inf, 3611, 7076, 11741, 19721, Inf)

rotulos <- c("0 - 3611", "3611 - 7076", "7076 - 11741", "11741 - 19721", "Mais de 19721")

temp$faixa_empregos <- cut(temp$total_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição de Empregos por Faixa - Varejo") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

tt <- sum(as.numeric(RAIS_est_geocoded_rich[grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), RAIS_est_geocoded_rich$clascnae20),]$estoque), na.rm = TRUE)
temp <- as.data.frame(RAIS_est_geocoded_rich) %>%
  filter(grepl(paste0("^(", paste0(prefixos, collapse = "|"), ")"), clascnae20)) %>%
  group_by(NomeDistri) %>%
  summarise(
    share_empregos = sum(as.numeric(estoque), na.rm = TRUE)/tt*100
  ) %>%
  ungroup()
left_join(temp, shp_sp, by = "NomeDistri") -> temp

temp <- st_as_sf(temp,crs = 4326)
format(quantile(temp$share_empregos, probs = seq(0, 1, by = 0.2)), scientific = FALSE)
##            0%           20%           40%           60%           80% 
## "0.003341646" "0.268866377" "0.479489099" "0.685309752" "0.991058002" 
##          100% 
## "4.744890066"
classIntervals(var = temp$share_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,082,785 possible partitions of this variable into 5 classes
## [0.003341646,0.4469142]   (0.4469142,0.8757588]    (0.8757588,1.453121] 
##                      53                      51                      19 
##     (1.453121,2.440763]      (2.440763,4.74489] 
##                       8                       4
limites <- c(-Inf, 0.44, 0.87, 1.45, 2.44, Inf)

rotulos <- c("0 - 0.44", "0.44 - 0.87", "0.87 - 1.45", "1.45 - 2.44", "Mais de 2.44")

temp$faixa_empregos <- cut(temp$share_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 0.5) +
  scale_fill_brewer(palette = "YlOrRd", name = "Faixa de Empregos") +
  labs(title = "Distribuição do Share Empregos por Faixa - Varejo") +
  theme_minimal() +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

Agregados_por_setores_demografia_BR <- read_excel("~/GitHub/AULAS/Dados/Agregados_por_setores_demografia_BR.xlsx")
shp_censo <- st_read("~/GitHub/AULAS/Dados/SP_setores_CD2022/SP_setores_CD2022.shp")
## Reading layer `SP_setores_CD2022' from data source 
##   `C:\Users\onurb\Documents\GitHub\AULAS\Dados\SP_setores_CD2022\SP_setores_CD2022.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 103319 features and 36 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -53.11011 ymin: -25.358 xmax: -44.16137 ymax: -19.77966
## Geodetic CRS:  SIRGAS 2000
if (st_crs(shp_sp) != st_crs(shp_censo)) {
  shp_censo <- st_transform(shp_censo, crs = st_crs(shp_sp))
  print("CRS transformado com sucesso!")
}
## [1] "CRS transformado com sucesso!"
shp_censo <- st_make_valid(shp_censo)
shp_sp <- st_make_valid(shp_sp)

# Filtra o shp_alvo, mantendo apenas o que está dentro do shp_filtro
shp_censo <- st_filter(shp_censo, shp_sp)

shp_censo_final <- st_join(shp_censo, shp_sp)
merge(Agregados_por_setores_demografia_BR, shp_censo_final, by.x = "CD_setor", by.y = "CD_SETOR") -> Agregados_por_setores_demografia_BR
temp <- as.data.frame(Agregados_por_setores_demografia_BR) %>%
  group_by(NomeDistri,Area_ha) %>%
  summarise(
    total_empregos = sum(as.numeric(V01006), na.rm = TRUE)
  ) %>%
  ungroup()
## Warning: There were 118 warnings in `summarise()`.
## The first warning was:
## ℹ In argument: `total_empregos = sum(as.numeric(V01006), na.rm = TRUE)`.
## ℹ In group 2: `NomeDistri = "Anhanguera"`, `Area_ha = 3339.95`.
## Caused by warning:
## ! NAs introduzidos por coerção
## ℹ Run `dplyr::last_dplyr_warnings()` to see the 117 remaining warnings.
## `summarise()` has grouped output by 'NomeDistri'. You can override using the
## `.groups` argument.
left_join(temp, shp_sp, by = "NomeDistri") -> temp
temp$total_empregos = temp$total_empregos / temp$Area_ha.x
temp <- st_as_sf(temp,crs = 4326)
quantile(temp$total_empregos, probs = seq(0, 1, by = 0.2))
##          0%         20%         40%         60%         80%        100% 
##   0.4276839  34.2360165  85.6035265 120.5051083 147.2236390 311.0734366
classIntervals(var = temp$total_empregos, n = 5, style = "jenks")
## style: jenks
##   one of 12,457,445 possible partitions of this variable into 5 classes
## [0.4276839,47.5089]   (47.5089,106.349]  (106.349,149.5444] (149.5444,199.0403] 
##                  36                  35                  39                  17 
## (199.0403,311.0734] 
##                   7
limites <- c(-Inf, 47.50, 106.34, 149.54, 199.04, Inf)

rotulos <- c("0 - 47.50", "47.50 - 106.34", "106.34 - 149.54", "149.54 - 199.04", "Mais de 199.04")

temp$faixa_empregos <- cut(temp$total_empregos,
                                 breaks = limites,
                                 labels = rotulos,
                                 right = TRUE)

library(ggplot2)

ggplot(data = temp) +
  geom_sf(aes(fill = faixa_empregos), shape = 21, color = "darkgray", size = 3) +
  scale_fill_brewer(palette = "YlOrRd", name = "População") +
  labs(title = "Densidade Populacional") +
  theme_minimal() +
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # --- ADICIONANDO O PIN AQUI ---
  geom_sf(data = pin_sf, 
          shape = 21,              # Formato de círculo com borda e preenchimento
          fill = "dodgerblue",     # Cor de preenchimento do pin
          size = 2,                # Tamanho do pin
          stroke = 1) +          # Espessura da borda
  geom_sf(data = shp_sp_cd, fill = NA, color = "black", size = 0.5) +
  # Trocando para o estilo náutico
  annotation_north_arrow(
    location = "tl",
    which_north = "true",
    style = north_arrow_nautical # <-- MUDANÇA AQUI
  )

ponto_referencia_geom <- st_point(c(-46.63390630217495, -23.550443536456253))
ponto_referencia_sf <- st_sfc(ponto_referencia_geom, crs = 4326)
Agregados_por_setores_demografia_BR <- read_excel("~/GitHub/AULAS/Dados/Agregados_por_setores_demografia_BR.xlsx")
shp_censo <- st_read("~/GitHub/AULAS/Dados/SP_setores_CD2022/SP_setores_CD2022.shp")
## Reading layer `SP_setores_CD2022' from data source 
##   `C:\Users\onurb\Documents\GitHub\AULAS\Dados\SP_setores_CD2022\SP_setores_CD2022.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 103319 features and 36 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -53.11011 ymin: -25.358 xmax: -44.16137 ymax: -19.77966
## Geodetic CRS:  SIRGAS 2000
if (st_crs(shp_sp) != st_crs(shp_censo)) {
  shp_censo <- st_transform(shp_censo, crs = st_crs(shp_sp))
  print("CRS transformado com sucesso!")
}
## [1] "CRS transformado com sucesso!"
shp_censo <- st_make_valid(shp_censo)
shp_sp <- st_make_valid(shp_sp)

# Filtra o shp_alvo, mantendo apenas o que está dentro do shp_filtro
shp_censo <- st_filter(shp_censo, shp_sp)

shp_censo_final <- st_join(shp_censo, shp_sp)
merge(Agregados_por_setores_demografia_BR, shp_censo_final, by.x = "CD_setor", by.y = "CD_SETOR") -> Agregados_por_setores_demografia_BR
Agregados_por_setores_demografia_BR <- st_as_sf(
  Agregados_por_setores_demografia_BR,
  crs = 4326
)
ponto_referencia_geom <- st_point(c(-46.63390630217495, -23.550443536456253))
ponto_referencia_sf <- st_sfc(ponto_referencia_geom, crs = 4326)
Agregados_por_setores_demografia_BR$distancia_marcozero <- format(st_distance(Agregados_por_setores_demografia_BR, ponto_referencia_sf), scientific = FALSE)
Agregados_por_setores_demografia_BR$distancia_marcozero = as.numeric(gsub("[^0-9.]", "", Agregados_por_setores_demografia_BR$distancia_marcozero))
Agregados_por_setores_demografia_BR$V01006 = as.numeric(Agregados_por_setores_demografia_BR$V01006)
## Warning: NAs introduzidos por coerção
dados_modelo <- Agregados_por_setores_demografia_BR %>% filter(distancia_marcozero > 0 & !is.na(distancia_marcozero))

group_by(dados_modelo, NomeDistri) %>%
  summarise(
    total_populacao = sum(as.numeric(V01006), na.rm = TRUE),
    distancia_marcozero = mean(distancia_marcozero, na.rm = TRUE)
  ) %>%
  ungroup() -> dados_modelo
modelo_densidade <- lm(total_populacao ~ distancia_marcozero, data = dados_modelo)
summary(modelo_densidade)
## 
## Call:
## lm(formula = total_populacao ~ distancia_marcozero, data = dados_modelo)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -203519  -78721  -40303   22173 1137882 
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         1.530e+05  2.462e+04   6.214 6.29e-09 ***
## distancia_marcozero 8.959e-01  1.117e+00   0.802    0.424    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 169200 on 132 degrees of freedom
## Multiple R-squared:  0.00485,    Adjusted R-squared:  -0.002689 
## F-statistic: 0.6433 on 1 and 132 DF,  p-value: 0.424
library(ggplot2)
library(mgcv)
## Carregando pacotes exigidos: nlme
## 
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
## 
##     collapse
## This is mgcv 1.8-42. For overview type 'help("mgcv-package")'.
# Crie o gráfico camada por camada
ggplot(data = dados_modelo, aes(x = distancia_marcozero, y = total_populacao)) +
  
  # 1. Adiciona os pontos de dispersão
  geom_point(color = "grey", shape = 16, alpha = 0.8) +
  
  # 2. Adiciona a linha de tendência suave (a curva)
  # Usamos o método 'gam' (Generalized Additive Model) que é ótimo para capturar curvas complexas
  geom_smooth(method = "gam", 
              formula = y ~ s(x, k=5), # s(x) cria uma curva suave
              se = FALSE,              # 'se = FALSE' remove a área de intervalo de confiança
              color = "black",         # Cor da linha
              linewidth = 0.8) +
  # regressa linear
  geom_smooth(method = "lm", 
              color = "red", 
              se = FALSE, 
              linewidth = 0.8) +
  
  # 4. Adiciona títulos e fontes
  labs(
    title = "Densidade Populacional de Uberlândia, 2022",
    caption = "Fonte: Cálculo próprio com dados do Censo IBGE."
  ) +
  
  # 5. Aplica um tema visual limpo e profissional
  theme_classic() +
  theme(
    # Adiciona a caixa preta ao redor do gráfico
    panel.border = element_rect(color = "black", fill = NA, linewidth = 1), 
    axis.title = element_text(size = 12),
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

RAIS_est_geocoded_rich$distancia_marcozero <- format(st_distance(RAIS_est_geocoded_rich, ponto_referencia_sf), scientific = FALSE)
RAIS_est_geocoded_rich$distancia_marcozero = as.numeric(gsub("[^0-9.]", "", RAIS_est_geocoded_rich$distancia_marcozero))
RAIS_est_geocoded_rich$estoque = as.numeric(RAIS_est_geocoded_rich$estoque)
dados_modelo <- RAIS_est_geocoded_rich %>% filter(distancia_marcozero > 0 & !is.na(distancia_marcozero))

group_by(dados_modelo, NomeDistri) %>%
  summarise(
    total_estoque = sum(as.numeric(estoque), na.rm = TRUE),
    distancia_marcozero = mean(distancia_marcozero, na.rm = TRUE)
  ) %>%
  ungroup() -> dados_modelo

modelo_densidade <- lm(total_estoque ~ distancia_marcozero, data = dados_modelo)
summary(modelo_densidade)
## 
## Call:
## lm(formula = total_estoque ~ distancia_marcozero, data = dados_modelo)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -40766 -29534 -19589   4557 376036 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         60106.7906  6923.0931   8.682 1.22e-14 ***
## distancia_marcozero    -0.7405     0.2525  -2.932  0.00396 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 57960 on 133 degrees of freedom
## Multiple R-squared:  0.06073,    Adjusted R-squared:  0.05367 
## F-statistic: 8.599 on 1 and 133 DF,  p-value: 0.003961
library(ggplot2)
library(mgcv)

# Crie o gráfico camada por camada
ggplot(data = dados_modelo, aes(x = (distancia_marcozero), y = total_estoque)) +
  
  # 1. Adiciona os pontos de dispersão
  geom_point(color = "grey", shape = 16, alpha = 0.8) +
  
  # 2. Adiciona a linha de tendência suave (a curva)
  # Usamos o método 'gam' (Generalized Additive Model) que é ótimo para capturar curvas complexas
  geom_smooth(method = "gam", 
              formula = y ~ s(x, k=5), # s(x) cria uma curva suave
              se = FALSE,              # 'se = FALSE' remove a área de intervalo de confiança
              color = "black",         # Cor da linha
              linewidth = 0.8) +
  
  # regressa linear
  geom_smooth(method = "lm", 
              color = "red", 
              se = FALSE, 
              linewidth = 0.8) +
  
  # 4. Adiciona títulos e fontes
  labs(
    title = "Densidade Populacional de Uberlândia, 2022",
    caption = "Fonte: Cálculo próprio com dados do Censo IBGE."
  ) +
  
  # 5. Aplica um tema visual limpo e profissional
  theme_classic() +
  theme(
    # Adiciona a caixa preta ao redor do gráfico
    panel.border = element_rect(color = "black", fill = NA, linewidth = 1), 
    axis.title = element_text(size = 12),
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold")
  )
## `geom_smooth()` using formula = 'y ~ x'